import React from "react";
import { connect } from 'dva';
import { getUuid } from "utils/comm";
import {
  Form,
  Row,
  Col,
  Input,
  Button,
  Popconfirm,
  Table,
  Popover,
} from "antd";
import moment from "moment";
import { openNotificationWithIcon } from "../../utils/comm";
import {
  defaultFormVariableState,
  getFormConfig,
  getFormSettings,
  typeOptions,
  defaultVariableSource,
} from './flowParametersHelper';
import styles from "./FlowParameters.less";

const checkRepeat = (key, datas, newData) => {
  const trim = (v = "") => v.trim();
  return datas.some(data => trim(data[key]) === trim(newData[key]));
};

export { typeOptions, getModelForms, isFormReferenced } from './flowParametersHelper';

// 转换成接口的格式
export const formatParameters = (flowParameters, modelForms) =>
  flowParameters.map(item => {
    const { uuid, variableSourceHint, formId, ...value } = item;
    const { type, defaultValue = "" } = value;
    if (defaultValue) {
      switch (type) {
        case "DATETIME":
          value.defaultValue = defaultValue.format("YYYY-MM-DD HH:mm:ss") || "";
          break;
        case "STA":
        case "ORG":
        case "ROL":
          value.defaultValue = JSON.stringify(value.defaultValue);
          break;
        default:
          break;
      }
    }
    if (formId) {
      const form = (modelForms || []).filter(({ formId: id }) => id === formId)[0];
      if (form) {
        value.formId = formId;
        value.formName = form.formName;
        value.formKey = form.formKey;
        value.formKey = form.formKey;
      }
    }
    if(value.variableSource==='form' && sessionStorage.getItem('isExternalForm') === 'externalForm')
    value.variableSource='externalForm'
      return value;
  });
// 转换成表格的格式
export const formatFormParameters = flowParameters => {
  return flowParameters.map(v => {
    const value = { ...v };
    const { type, defaultValue } = value;
    if (defaultValue || defaultValue === 0) {
      switch (type) {
        case "DATETIME":
          value.defaultValue = moment(defaultValue, "YYYY-MM-DD HH:mm:ss");
          break;
        case "INT":
          value.defaultValue = parseInt(defaultValue, 10);
          break;
        case "DOUBLE":
          value.defaultValue = parseFloat(defaultValue);
          break;
        case "STA":
        case "ORG":
        case "ROL":
          value.defaultValue = JSON.parse(defaultValue);
          break;
        default:
          break;
      }
    }
    value.uuid = getUuid();
    return value;
  });
};
// 需要表格格式的record
export const renderDefaultValue = (v, record) => {
  const { type } = record;
  switch (type) {
    case "DATETIME":
      return (v && v.format("YYYY-MM-DD HH:mm:ss")) || "";
    case "STA":
    case "ORG":
    case "ROL":
      return (v && v.label) || "";
    default:
      return v;
  }
};
const modifySpec = "编辑流程变量";
const deleteSpec =
  "删除表格中选中的变量，已关联用户任务节点办理人的变量无法删除";
const deleteAllSpec =
  "删除表格中所有变量，已关联用户任务节点办理人的变量无法删除";

@connect(({ loading }) => ({
  loadingFormSetting: loading.effects['FormConfigure/getFormDetail'],
}))
@Form.create()
class FlowParameters extends React.Component {

  openNotificationWithIcon = openNotificationWithIcon.bind(this);

  formConfig = getFormConfig.bind(this);

  state = {
    editingIndex: -1,
    selectedRowKeys: [],
    selectedType: null,
    edittingAssociatedVariable: false,
   ...defaultFormVariableState,
  };

  cashedColumns = null;

  getColumns = () => {
    // const { editable } = this.props;
    // window.form = this.props.form;
    if (this.cachedColumns) {
      return this.cachedColumns;
    }

    const cachedColumns = [
      { title: "变量名称",
        dataIndex: "name",
        render: this.renderTitle,
        align: "center",
      },
      { title: "变量编码",
        dataIndex: "code",
        align: "center",
      },
      {
        title: "变量类型",
        dataIndex: "type",
        align: "center",
        render: v => {
          const typeOption = typeOptions.filter(o => o.value === v)[0] || {
            label: "",
          };
          return typeOption.label;
        },
      },
      {
        title: "添加方式",
        dataIndex: "variableSource",
        align: "center",
        render: v =>{
          return v === "form" ? "表单" : "手动";
        },
      },
      {
        title: "详情",
        dataIndex: "uuid",
        align: "center",
        render: (v, o) => {
          const type = typeOptions.filter(typeO => typeO.value === o.type)[0].label || "";
          return (
            <Popover
              title='详情'
              trigger="hover"
              placement="right"
              content={
                <div>
                  变量名称：
                  {o.name}
                  <br />
                  变量编码：
                  {o.code}
                  <br />
                  变量类型：
                  {type}
                  <br />
                  添加方式：
                  {o.variableSource === "form" ? "表单" : "手动"}
                  <br />
                  默认值：
                  {this.getDefaultValueFromType(type, o.defaultValue)}
                  <br />
                  变量说明：
                  {o.description}
                </div>
            }
            >
              <div style={{color: 'rgb(78,138,184)' }}>查看</div>
            </Popover>
          )
        },
      },
    ];
/*    if (editable) {
      cachedColumns.concat([
        {
          title: "默认值",
          dataIndex: "defaultValue",
          render: renderDefaultValue,
        },
        {
          title: "说明",
          dataIndex: "description",
          render: v => (
            <div className={styles.desc} title={v}>
              {v}
            </div>
          ),
        },
      ]);
    } */
    this.cachedColumns = cachedColumns;
    return this.cachedColumns;
  };

  getDefaultValueFromType = (type, defaultValue) =>{
    if (type === "日期时间型"){
      return moment(defaultValue).format('YYYY-MM-DD HH:mm:ss');
    } else if (type === "人员" || type ==="组织" || type === "角色"){
      return defaultValue?.label;
    }

    return defaultValue;
}

  getFields() {
    const { selectedType, edittingAssociatedVariable } = this.state;
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const _formConfig = this.formConfig();

    if (selectedType) {
      const type = typeOptions.filter(({ value }) => selectedType === value)[0];
      if (type) {
        let defaultValueIndex;
        _formConfig.forEach(({ key }, idx) => {
          if(key === 'defaultValue') {
            defaultValueIndex = idx;
          }
        });
        _formConfig.splice(defaultValueIndex, 1, {
          options: {},
          ...type.next,
          decoratorKey: "defaultValue",
          label: "默认值",
        });
      }
    }

    return _formConfig.map(config => {
      const {
        component,
        decoratorKey,
        itemProps,
        key,
        label,
        options,
        placeholder,
      } = config;
      return (
        <Col span={12} key={key}>
          <Form.Item label={label}>
            {getFieldDecorator(
              decoratorKey || key,
              options,
            )(
              component || (
                <Input
                  placeholder={placeholder}
                  {...itemProps}
                  {...((key === "code" || key === "name") &&
                  edittingAssociatedVariable
                    ? {
                        // title: '已关联用户任务办理人的变量不能编辑变量编码',
                        disabled: true,
                      }
                    : {})}
                />
              ),
            )}
          </Form.Item>
        </Col>
      );
    });
  }

  renderTitle = (value, record, rowIndex) => {
    // click row
    const { editable } = this.props;
    const { editingIndex } = this.state;
    if (!editable || editingIndex > -1) {
      return <span style={{ whiteSpace: 'pre' }}>{value}</span>;
    }
    return (
      <span
        style={{
          color: "#608EFF",
          cursor: "pointer",
          textDecoration: "underline",
          whiteSpace: 'pres',
        }}
        title="编辑"
        onClick={() => {
          const { type: selectedType, code } = record;
          const { editingIndex: i } = this.state;
          const { modelVariableRef, value: dataSources } = this.props;
          if (i > -1) {
            return;
          }
          let _editingIndex = rowIndex;
          while (
            dataSources[_editingIndex].code !== code &&
            _editingIndex < dataSources.length
          ) {
            _editingIndex += 5; // pageSize
          }
          const edittingAssociatedVariable = !!(
            modelVariableRef && modelVariableRef[code]
          );
          this.setState(
            {
              selectedType,
              editingIndex: _editingIndex,
              edittingAssociatedVariable,
            },
            () => {
              const { form } = this.props;
              const { uuid, ...formValues } = record;
              form.setFieldsValue(formValues);
            },
          );
        }}
      >
        {value}
      </span>
    );
  };

  resetForm = (variableSource = defaultVariableSource) => {
    const { form } = this.props;
    form.resetFields();
    form.setFieldsValue({
      variableSource,
      variableSourceHint: variableSource,
    })
    this.setState({
      editingIndex: -1,
      selectedRowKeys: [],
      selectedType: null,
      edittingAssociatedVariable: false,
      ...defaultFormVariableState,
    });
  };

  onSave = () => {
    const { editingIndex } = this.state;
    const { form, onChange, value, onError = () => {} } = this.props;
    form.validateFields((errors, values) => {
      if (errors) {
        return;
      }
      const newValue = [...value];

      const currentValue = {
        ...values,
        uuid: getUuid(),
      };

      if (editingIndex > -1) {
        newValue[editingIndex] = currentValue;
      } else {
        if (checkRepeat("name", newValue, values)) {
          onError(`变量名称 ${values.name} 已存在`);
          return;
        }
        if (checkRepeat("code", newValue, values)) {
          onError(`变量编码 ${values.code} 已存在`);
          return;
        }
        newValue.unshift(currentValue);
      }
      this.resetForm();
      onChange(newValue);
    });
  };

  onEdit = () => {
    const { selectedRowKeys } = this.state;
    const { value = [], form } = this.props;
    const formValue = value.filter(v => v.uuid === selectedRowKeys[0])[0]
    const index = value.findIndex(v => v.uuid === selectedRowKeys[0])

    // eslint-disable-next-line react/no-unused-state
    this.setState({editingIndex: index, variableSource: formValue?.variableSource});

    form.resetFields(["type", "defaultValue", "formId"]);
    if (formValue.formId){
      getFormSettings.call(this, formValue.formId)
    }
    if (formValue.type) {
      this.setState({selectedType: formValue.type})
    }
    setTimeout( () => form.setFieldsValue({
      code: formValue.code,
      name: formValue.name,
      type: formValue.type,
      formId: formValue.formId,
      variableSource: formValue.variableSource,
      variableSourceHint: formValue.variableSource,
      defaultValue: formValue.defaultValue,
      description: formValue.description,
    }),200);

  }

  renderButtons() {
    const { editingIndex, selectedRowKeys } = this.state;
    const { value = [], modelVariableRef = {} } = this.props;
    return (
      <Col span={12}>
        <Row
          align="bottom"
          justify="space-around"
          style={{ height: 52 }}
          type="flex"
        >
          <Button onClick={this.onSave}>
            {editingIndex > -1 ? "保存" : "添加"}
          </Button>
          {editingIndex > -1 ? (
            <Button onClick={() => this.resetForm()}>取消</Button>
          ) : (
            <>
              {selectedRowKeys.length > 0 ? (
                <Popconfirm
                  placement="top"
                  title="请确认是否删除当前选中变量"
                  onConfirm={() => {
                    const { selectedRowKeys: selectedKeys } = this.state;
                    const { value: _value = [], onChange } = this.props;
                    this.setState({ selectedRowKeys: [] }, () => {
                      onChange(
                        _value.filter(v =>
                          selectedKeys.every(k => k !== v.uuid),
                        ),
                      );
                    });
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button title={deleteSpec}>删除</Button>
                </Popconfirm>
              ) : (
                <Button disabled title={deleteSpec}>
                  删除
                </Button>
              )}
              {value.length > 0 ? (
                <Popconfirm
                  placement="top"
                  title="请确认是否删除所有变量"
                  onConfirm={() => {
                    const { value: _value = [], onChange } = this.props;
                    this.setState({ selectedRowKeys: [] }, () => {
                      onChange(_value.filter(v => !!modelVariableRef[v.code]));
                    });
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button title={deleteAllSpec}>全删</Button>
                </Popconfirm>
              ) : (
                <Button disabled title={deleteAllSpec}>
                  全删
                </Button>
              )}
              {selectedRowKeys.length === 1 ? (
                <Button title={modifySpec} onClick={() => this.onEdit()}>编辑</Button>
              ) : (
                <Button disabled>编辑</Button>
              )
              }
            </>
          )}
        </Row>
      </Col>
    );
  }

  render() {
    const {
      selectedRowKeys,
      edittingAssociatedVariable,
      editingIndex,
    } = this.state;
    // const { selectedRowKeys, edittingAssociatedVariable } = this.state;
    const {
      editable = true,
      modelVariableRef = {},
      onChange,
      value,
    } = this.props;
    let hint = `*此变量已关联用户任务办理人, 仅支持编辑默认值和说明`;
    let v;
    if (editable && edittingAssociatedVariable) {
      const nodes = modelVariableRef[value[editingIndex].code];
      if (nodes) {
        v = (nodes[0] || {}).label || "";
      }
      if (v) {
        hint = (
          <>
            *此变量已关联名称为
            <span style={{ fontWeight: "bold" }}>{v}</span>
            的用户任务办理人, 仅支持编辑默认值和说明
          </>
        );
      }
    }
    return (
      <>
        {editable ? (
          <Row gutter={24}>
            <Form className={styles.advance_form}>{this.getFields()}</Form>
            {this.renderButtons()}
          </Row>
        ) : null}
        {editable && edittingAssociatedVariable ? (
          <div style={{ color: "red", fontSize: "12px" }}>{hint}</div>
        ) : null}
        <Table
          rowKey={editable ? "uuid" : "code"}
          columns={this.getColumns()}
          dataSource={value}
          pagination={{
            pageSize: 5,
          }}
          rowSelection={{
            fixed: true,
            getCheckboxProps: ({ code }) => {
              const disabled = !!modelVariableRef[code];
              const result = { disabled };
              /*
              if (disabled) {
                result.title = `用户任务${modelVariableRef[code].name}关联了此变量，无法删除`;
              }
              */
              return result;
            },
            selectedRowKeys,
            onChange: (keys, rows) => {
              this.setState({ selectedRowKeys: keys });
              if (!editable) {
                onChange(rows);
              }
            },
          }}
        />
      </>
    );
  }
}

export default FlowParameters;
